import { BadRequestException, Injectable } from '@nestjs/common';
import { CreateChangeuserDto } from './dto/create-changeuser.dto';
import { UpdateChangeuserDto } from './dto/update-changeuser.dto';
import { PrismaService } from '@/prisma/prisma.service';
import { changeUserInfoPassWordDto } from './dto/changeUserPassWord.dto';
import { hash, verify } from 'argon2';
import { findUserInfoPassWord } from './dto/findPassWord.dto';

@Injectable()
export class ChangeuserService {
  constructor(private prisma: PrismaService) {}
  //修改用户信息
  async update(dto: CreateChangeuserDto, req: any) {
    const user = await this.prisma.user.update({
      where: {
        id: req.user.id,
      },
      data: {
        email: dto.email,
        name: dto.name,
        gender: dto.gender,
      },
    });
    delete user.passWord;
    delete user.userName;
    return user;
  }
  //修改密码
  async updateUserPassWord(dto: changeUserInfoPassWordDto, req: any) {
    const user = await this.prisma.user.findFirst({
      where: {
        id: req.user.id,
      },
    });
    if (!(await verify(user.passWord, dto.passWord))) {
      throw new BadRequestException('旧密码输入错误');
    } else {
      if (dto.passWord == dto.newPassWord) {
        throw new BadRequestException('旧密码和新密码不能一致');
      } else {
        user.passWord = await hash(dto.newPassWord);
        const updateUser = await this.prisma.user.update({
          where: {
            id: user.id,
          },
          data: {
            ...user,
          },
        });
        return updateUser;
      }
    }
  }
  //找回密码
  async findUserPassWord(dto: findUserInfoPassWord) {
    //找到用户
    const user = await this.prisma.user.findFirst({
      where: {
        email: dto.email,
      },
    });
    if (!user) {
      throw new BadRequestException('很抱歉,并没有该账户');
    }
    user.passWord = await hash(dto.passWord);
    const newUser = await this.prisma.user.update({
      where: {
        id: user.id,
      },
      data: {
        ...user,
      },
    });
    delete newUser.passWord;
    delete newUser.userName;
    return newUser;
  }
}
